package com.oriole.oauth2.server.config;

import com.oriole.common.constant.Constants;
import com.oriole.entity.security.OrioleUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.oauth2.provider.token.DefaultUserAuthenticationConverter;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Date: 2020/8/12 22:53
 * description: 自定义把需要的用户的信息放入token中
 */
public class OrioleDefaultUserAuthenticationConverter extends DefaultUserAuthenticationConverter {

    @Override
    public Map<String, ?> convertUserAuthentication(Authentication authentication) {
        Map<String, Object> response = new LinkedHashMap<>();
        response.put(USERNAME, authentication.getName());
        // token中新增user_id
        if (authentication.getPrincipal() instanceof OrioleUserDetails) {
            OrioleUserDetails userDetails = (OrioleUserDetails) authentication.getPrincipal();
            response.put(Constants.USER_ID, userDetails.getId());
        }
        if (authentication.getAuthorities() != null && !authentication.getAuthorities().isEmpty()) {
            response.put(AUTHORITIES, AuthorityUtils.authorityListToSet(authentication.getAuthorities()));
        }
        return response;
    }

}
